/**
 * 测试辅助函数
 */

/**
 * 管理员登录
 */
async function adminLogin(page) {
  await page.goto('/login');
  await page.fill('input[placeholder*="用户名"]', 'admin');
  await page.fill('input[type="password"]', 'admin123');
  await page.click('button:has-text("登录")');
  await page.waitForURL(/\/admin/, { timeout: 5000 });
}

/**
 * 学生登录
 */
async function studentLogin(page, username = 'nice', password = 'nice') {
  await page.goto('/login');
  await page.fill('input[placeholder*="用户名"]', username);
  await page.fill('input[type="password"]', password);
  await page.click('button:has-text("登录")');
  await page.waitForURL(/\/dashboard/, { timeout: 5000 });
}

/**
 * 检查控制台错误
 */
function setupErrorListeners(page) {
  const errors = [];
  
  page.on('console', msg => {
    if (msg.type() === 'error') {
      errors.push({ type: 'console', message: msg.text() });
    }
  });
  
  page.on('pageerror', error => {
    errors.push({ type: 'page', message: error.message });
  });
  
  page.on('requestfailed', request => {
    errors.push({ 
      type: 'request', 
      url: request.url(), 
      error: request.failure()?.errorText 
    });
  });
  
  return errors;
}

/**
 * 检查API响应错误
 */
function setupAPIMonitor(page) {
  const failedRequests = [];
  
  page.on('response', response => {
    if (response.status() >= 400) {
      failedRequests.push({
        url: response.url(),
        status: response.status(),
        statusText: response.statusText()
      });
    }
  });
  
  return failedRequests;
}

/**
 * 截图并保存
 */
async function takeScreenshot(page, name) {
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
  const filename = `screenshots/${name}-${timestamp}.png`;
  await page.screenshot({ path: filename, fullPage: true });
  console.log(`📸 截图已保存: ${filename}`);
}

/**
 * 等待并检查元素
 */
async function waitAndCheck(page, selector, timeout = 5000) {
  try {
    await page.waitForSelector(selector, { timeout, state: 'visible' });
    return true;
  } catch (error) {
    console.log(`⚠️  元素未找到: ${selector}`);
    return false;
  }
}

module.exports = {
  adminLogin,
  studentLogin,
  setupErrorListeners,
  setupAPIMonitor,
  takeScreenshot,
  waitAndCheck
};

